package com.breeze.components.socket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.breeze.components.socket.util.WebSocketUtil;
import com.breeze.components.socket.vo.WebSocketRequest;
import com.breeze.components.socket.vo.WebSocketResponse;
import java.util.Date;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

/**
 * WebSocketEndpoint基类
 *
 * @author breeze
 */
@Slf4j
public abstract class BaseWebSocketHandler extends AbstractWebSocketHandler {

  public void connect(String identifier, WebSocketSession session) {
    try {
      if (StrUtil.isEmpty(identifier)) {
        return;
      }
      WebSocketManager websocketManager = getWebSocketManager();
      WebSocket webSocket = new WebSocket();
      webSocket.setIdentifier(identifier);
      // 用支持并发的session
      webSocket.setSession(WebSocketUtil.decoratorSession(session));
      webSocket.setLastHeart(new Date());
      // id一样session不一样则覆盖
      websocketManager.put(identifier, webSocket);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }

  public void disconnect(String identifier) {
    getWebSocketManager().remove(identifier);
  }

  public void receiveMessage(String identifier, String message) {
    WebSocketRequest request = JSON.parseObject(message, WebSocketRequest.class);
    if (StrUtil.isEmpty(request.getCmd())) {
      return;
    }
    WebSocketManager webSocketManager = getWebSocketManager();
    WebSocket socket = webSocketManager.get(identifier);
    // ping 心跳监测
    if (webSocketManager.isPing(request) && Objects.nonNull(socket)) {
      WebSocketResponse<String> msg =
          WebSocketResponse.ok(request.getCmd(), webSocketManager.pong());
      WebSocketUtil.sendMessage(socket.getSession(), JSON.toJSONString(msg));
      WebSocket webSocket = webSocketManager.get(identifier);
      // 更新心跳时间
      if (Objects.nonNull(webSocket)) {
        webSocket.setLastHeart(new Date());
      }
      return;
    }
    // 收到其他消息的时候
    webSocketManager.onMessage(identifier, request);
  }

  protected WebSocketManager getWebSocketManager() {
    return SpringUtil.getBean(WebSocketManager.WEBSOCKET_MANAGER_NAME, WebSocketManager.class);
  }
}
